extends CharacterBody2D
class_name PlanePlayer
var bullet:PackedScene = preload("res://scn/bullet.tscn")


@onready var bullets:Node2D = $"../Bullets"
@onready var playerHpTip:Node2D = $"../PlayerHp"
@onready var attack_audio:AudioStreamPlayer2D = $AudioStreamPlayer2D
@onready var plane_size:Vector2 = Vector2(30,21)
@onready var viewport = get_viewport_rect()

# 血量
var hp:int


signal game_over

func _ready():
	hp = GlobalConstant.PLAYER_MAX_HP
	playerHpTip.updateScore(hp)
	planeInit()

func planeInit():
	position = Vector2(200,650)
	$AnimatedSprite2D.play("default")
	var moveTween = get_tree().create_tween()
	moveTween.tween_property(self,"position:y",self.get_global_position().y - 120,1).set_ease(Tween.EASE_IN).set_trans(Tween.TRANS_LINEAR)
	moveTween.tween_callback(planeInitComplete)
	var transparentTween = get_tree().create_tween()

func planeInitComplete():
	GlobalConstant.PLAYER_MOVE = true
	await get_tree().create_timer(1).timeout
	# 初始化完成1秒无敌时间结束
	GlobalConstant.PLAYER_INVINCIBLE = false

func _physics_process(delta):
	# 移动处理
	move_process(delta)
	
	# 射击事件
	shooting(delta)
	
	# 移动
	move_and_slide()
	
func move_process(delta):
	if not GlobalConstant.PLAYER_MOVE:
		return
	var directionX = Input.get_axis("left", "right")
	var directionY = Input.get_axis("up", "down")
	var direction = Vector2(directionX,directionY)
	position += direction.normalized() * GlobalConstant.PLAYER_SPEED * delta
	position.x = clamp(position.x,plane_size.x,viewport.size.x - plane_size.x)
	position.y = clamp(position.y,plane_size.y,viewport.size.y - plane_size.y)
	

var attack_interval: float = 1 / GlobalConstant.ATTACK_SPEED
	
func shooting(delta):
	if attack_interval > 0:
		attack_interval -= delta
	
	if Input.is_action_pressed("space") and GlobalConstant.PLAYER_MOVE:
		generateBullet()
	pass

func generateBullet():
	if attack_interval > 0:
		return
	attack_interval = 1 / GlobalConstant.ATTACK_SPEED
	
	var bulletExample = bullet.instantiate()
	var selfPosition = self.get_global_position()
	bulletExample.position = selfPosition
	bullets.add_child(bulletExample)
	# 播放音效
	attack_audio.play()

# 被攻击特效
func byAttacked():
	if GlobalConstant.PLAYER_INVINCIBLE:
		return
	GlobalConstant.PLAYER_INVINCIBLE = true
	GlobalConstant.PLAYER_MOVE = false
	hp = clamp(hp-1,0,GlobalConstant.PLAYER_MAX_HP)
	if hp <=0:
		# 结束游戏
		game_over.emit()
		return
	playerHpTip.updateScore(hp)
	$AnimatedSprite2D.play("die")
	await get_tree().create_timer(2).timeout
	planeInit()
